<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);

class manage extends admin
{

    private $db,$tsmodel,$talent_pic_model;

    public $siteid;

    public $agency_branch;

    public $agency_type;

    function __construct()
    {
        parent::__construct();
        pc_base::load_app_func('global');
        $this->db = pc_base::load_model('pass_game_model'); // 加载pass_game_model
        $this->tsmodel = pc_base::load_model('pass_talent_model');
        $this->talent_pic_model = pc_base::load_model('pass_talent_pic_model');
        $this->siteid = get_siteid(); // 获取当前站点ID
        $model_setting=pc_base::load_model('site_setting_model');//加载设置类model
        $this->t_type = $model_setting->getValue("talent_type",$this->siteid);//获取人才类型
        $this->admin_username = param::get_cookie('admin_username'); // 获取当前登录的管理员
    }

    /**
     * 关卡列表
     * 
     */
    public function init()
    {
        $show_dialog = $show_validator = true;
        $show_header = '';
        $where .= " status = 1 and siteid =" . $this->siteid;
        //搜索框
        $name = empty($_GET['name']) ?'':$_GET['name'] ;#关卡名称
        if(!empty($name)){
            $where .= ' and name like "%'.$name.'%"';
        }

        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;#获取页码
        //查询关卡信息
        $gameinfo = $this->db->select($where,"*","", 'id DESC , list_order DESC');#根据 update_time 降序排列
        $gameinfo=getTreeList($gameinfo,0);
        //获取管理员信息
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $administrators = $admin_model->getRealnameInfo();
        //数据重构：加上最后编辑者信息
        foreach ($gameinfo as $key=>$value){
            foreach ($administrators as $key2=>$value2){
                if($value['updated_by'] == $key2){
                    $value['publisher'] = $value2;
                    $gameinfo[$key] = $value;
                    break;
                }
            }
        }
       $pages = $this->db->pages;
        include $this->admin_tpl('pass_game_list');
    }

    /**
     * 关卡添加
     */
    public function add()
    {
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['list_order']   =  0;#listorder排序字段初始值给1
            $data['created_by']  =  $_SESSION['userid'];#管理用户ID
            $data['updated_by']  =  $_SESSION['userid'];#管理用户ID
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;#状态（0：禁用  1：可用  2：删除）
            $result = $this->db->insert($data,true);
            if ($result) {
                $id = $this->db->insert_id();
            	//记录行为日志
            	$log_content = '<span style="color:green;">添加关卡</span>[关卡id：'.$id.'；关卡名称：'.$data['name'].']';
            	$this->manage_admin_log($log_content);
                $url='?m=pass_game&c=manage&a=init';
                showmessage(L('add_success'), $url);
            } else {
                showmessage(L('add_error'), HTTP_REFERER);
            }
        } else {
            $show_dialog = $show_validator = true;
            $show_header = '';
            $id = isset($_GET['id']) ? $_GET['id'] :0;

            //$show_dialog = $show_validator = true;
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);
            include $this->admin_tpl('pass_game_add');
        }
    }

    /**
     *关卡编辑
     */
    public function edit()
    {
        //如果没获取到id，则视为非法请求
        $id = isset($_GET['id']) ? $_GET['id'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
        $upinfo = $_POST['data'];
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['updated_by'] =  $_SESSION['userid'];
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;#状态（0：禁用  1：可用  2：删除）
            $result = $this->db->update($data, array(
                'id' => $id
            ));
            if ($result) {
            	//记录行为日志
            	$log_content = '<span style="color:blue;">修改关卡</span>[关卡id：'.$id.'；关卡名称：'.$data['name'].']';
            	$this->manage_admin_log($log_content);
                $url='?m=pass_game&c=manage&a=init';
                showmessage(L('edit_success'), $url);
            } else {
                showmessage(L('edit_error'), HTTP_REFERER);
            }
        } else {
            $data = $this->db->get_one(array(
                'id' => $id
            ));
            $show_dialog = $show_validator = true;
            $show_header = '';
            include $this->admin_tpl('pass_game_edit');
        }
    }

    /**
     * 删除、批量删除关卡
     */
    public function del()
    {
        //如果没获取到id，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $name = $_REQUEST['name']?$_REQUEST['name']:'请联系管理员！';
        if (is_array($id)) {
            foreach ($id as $k => $v) {

                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        }
        //关卡绑定的人才硬删除、人才绑定的图片硬删除
        $talent_ids = $this->tsmodel->select(' pid in('.$id.')','tid');#查询该关卡绑定人才的id
        //关卡关联的人才非空才进行删除操作
        if(!empty($talent_ids)){
            $talent_ids_str = '';
            foreach ($talent_ids as $key=>$value){
                $talent_ids_str .= ','.$value['tid'];
            }
            $talent_ids_str = substr($talent_ids_str, 1);
            $this->talent_pic_model->delete(' tid in('.$talent_ids_str.')');#删除人才绑定的图片
        }
        
        $this->tsmodel->delete(' pid in('.$id.')');#删除关卡绑定的人才
        //关卡软删除
        $result = $this->db->update(array(
            'status' => '2'#状态（0：禁用  1：可用  2：删除）
        ), "id in ('$id')");
        
        if ($result) {
        	//记录行为日志
        	$del_id = explode('\',\'', $id);
        	$new_id = implode(',', $del_id);
        	$log_content = '<span style="color:red;">删除关卡</span>[关卡id：'.$new_id.'；关卡名称：'.$name.']';
        	$this->manage_admin_log($log_content);
            showmessage(L('del_success'), HTTP_REFERER);
        } else {
            showmessage(L('del_error'), HTTP_REFERER);
        }
    }

    /*
     * 关卡详情
     */
    public function view()
    {
        //如果没获取到id，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $data = $this->db->get_one(array(
            'id' => $id
        ));
        $show_header = '';
        include $this->admin_tpl('pass_game_view');
    }

    /*
     * 关卡关联人才-列表
     */
    public function pass_talent()
    {
        $pass_talent_model=pc_base::load_model('pass_talent_model');
        $pass_talent_pic_model=pc_base::load_model('pass_talent_pic_model');
        
        $types = $this->t_type;
        
        $sql="select n.*,t.id as cid,t.tid,t.pid,t.image_vertical as image_shuxing from nsrweb_pass_talent as t LEFT JOIN nsrweb_talent as n on t.tid =n.id where n.status=1 ";
        $sql .= "  and n.siteid =" . $this->siteid;
        if (isset($_GET['user_name']) && !empty($_GET['user_name'])) {
            $name = trim($_GET['user_name']);
            $sql .= " and `real_name` like '%$name%' ";
        }
        $column_name = trim($_GET['name']);
        if (isset($_GET['talent_type']) && !empty($_GET['talent_type'])) {
            switch ($_GET['talent_type']) {
                case '1':
                    $sql .= " and n.is_student = 1";
                    break;
                case '2':
                    $sql .= " and n.is_signed_model = 1";
                    break;
                case '3':
                    $sql .= " and n.is_hot = 1";
                    break;
                case '4':
                    $sql .= " and n.is_judge = 1";
                    break;
                case '5':
                    $sql .= " and n.is_guest = 1";
                    break;
                case '6':
                    $sql .= " and n.is_star = 1";
                    break;
                case '7':
                    $sql .= " and n.is_mentor = 1";
                    break;
                case '8':
                    $sql .= " and n.is_moter = 1";
                    break;
                default:
                    break;
            }
        }
        
        $sql .= " order by t.id desc,t.tid desc,n.id DESC ";
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $talentinfo = $this->db->my_listinfo($sql, $page, 10);
        
        $pages = $this->db->pages;
        $show_header = '';
        include $this->admin_tpl('pass_talent_list');
    }

    /**
     * 排序
     */
    public function listorder() {
        if(isset($_GET['dosubmit'])) {
            foreach($_POST['listorders'] as $id => $listorder) {
                $this->db->edit(array('list_order'=>$listorder),$id);
                //添加缓存
                //$this->db->redisCache($id);
            }
        	//记录行为日志
        	$log_content = '<span style="color:orange;">关卡排序</span>';
        	$this->manage_admin_log($log_content);
            showmessage(L('operation_success'));
        } else {
            showmessage(L('operation_failure'));
        }
    }

    /**
     * 用户游戏结果管理
     */
    public function user_game_list ()
    {
        $pass_game_result = pc_base::load_model('pass_game_result_model');
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $where = " id > 0 ";
        $passGameList = $this->db->getGameList();
        if(isset($_GET['user_name']) && $_GET['user_name']) {
            $user_name = trim($_GET['user_name']);
            $where .= " and `user_name` like '%$user_name%' ";
        }
        if(isset($_GET['is_success']) && $_GET['is_success']) {
            $is_success = intval($_GET['is_success']);
            if ($is_success == 1) {
               $where .= " and is_success = " . $is_success; 
            } else {
               $where .= " and is_success = 0 "; 
            }
        }
        if(isset($_GET['platform']) && $_GET['platform']) {
            $platform = intval($_GET['platform']);
            $where .= " and platform = " . $platform;
        }
        if(isset($_GET['pass_game_id']) && $_GET['pass_game_id']) {
            $pass_game_id = intval($_GET['pass_game_id']);
            $where .= " and pass_game_id = " . $pass_game_id;
        }
        $lists = $pass_game_result->listinfo($where,'id DESC',$page,10);
        foreach ($lists as $k => $v) {
            $info = $this->db->get_one(array('id'=>$v['pass_game_id']));
            $lists[$k]['pass_name'] = $info['name'];
            $pass_talent_pic_ids = explode(',',$v['pass_talent_pic_ids']);
            if (empty($pass_talent_pic_ids)) {
                $lists[$k]['pass_pic'] = '';
            } else {
                $infoPic = $this->talent_pic_model->get_one(array('id'=>$pass_talent_pic_ids[0]));
                $lists[$k]['pass_pic'] = $infoPic['pic_url'];
            }
        }
        $pages = $pass_game_result->pages;
        include $this->admin_tpl('user_game_list');
    }

    /**
     * 用户游戏结果统计
     */
    public function user_game_analysis ()
    {
        //引入 pass_game_result_model
        $pass_game_result = pc_base::load_model('pass_game_result_model');
        if(isset($_COOKIE['all_play_num']) && !empty($_COOKIE['all_play_num'])){
            $today_user_num = $_COOKIE['today_user_num'];
            $yesterday_user_num = $_COOKIE['yesterday_user_num'];
            $last_week_user_num = $_COOKIE['last_week_user_num'];
            $last_month_user_num = $_COOKIE['last_month_user_num'];
            $all_user_num = $_COOKIE['all_user_num'];


            $today_play_num = $_COOKIE['today_play_num'];
            $yesterday_play_num = $_COOKIE['yesterday_play_num'];
            $last_week_play_num = $_COOKIE['last_week_play_num'];
            $last_month_play_num = $_COOKIE['last_month_play_num'];
            $all_play_num = $_COOKIE['all_play_num'];
            $pass_result = getcache('pass_result');
        }else{
            //组装今日、昨日、过去一周、过去一月查询SQL语句
            $date_today = date('Y-m-d').' 00:00:00';
            $date_yesterdat_begin = date('Y-m-d',time()-24*60*60).' 00:00:00';
            $date_yesterday_end = date('Y-m-d',time()-24*60*60).' 23:59:59';
            $date_last_week_begin = date('Y-m-d',time()-7*24*60*60).' 00:00:00';
            $date_last_week_end = date('Y-m-d').' 00:00:00';
            $date_last_month_begin = date('Y-m-d',time()-30*24*60*60).' 00:00:00';
            $date_last_month_end = date('Y-m-d H:i:s');
            
            $where_today =" create_time > '".$date_today."'";
            $where_yesterday =" create_time > '".$date_yesterdat_begin."' and create_time < '".$date_yesterday_end."'";
            $where_last_week =" create_time > '".$date_last_week_begin."' and create_time < '".$date_last_week_end."'";
            $where_last_month =" create_time > '".$date_last_month_begin."' and create_time < '".$date_last_month_end."'";
            
            //今日闯关用户个数
            $today_user_result = $pass_game_result->select($where_today,'count(DISTINCT(user_id)) as today_user_nums');
            //昨日闯关用户个数
            $yesterday_user_result = $pass_game_result->select($where_yesterday,'count(DISTINCT(user_id)) as yesterday_user_nums');
            //过去一周闯关用户个数
            $last_week_user_result = $pass_game_result->select($where_last_week,'count(DISTINCT(user_id)) as last_week_user_nums');
            //过去一月闯关用户个数
            $last_month_user_result = $pass_game_result->select($where_last_month,'count(DISTINCT(user_id)) as last_month_user_nums');
            //全部闯关用户个数
            $all_user_result = $pass_game_result->select('','count(DISTINCT(user_id)) as all_user_nums');
            
            //今日闯关个数
            $today_play_result = $pass_game_result->select($where_today,'count(id) as today_play_nums');
            //昨日闯关个数
            $yesterday_play_result = $pass_game_result->select($where_yesterday,'count(id) as yesterday_play_nums');
            //过去一周闯关个数
            $last_week_play_result = $pass_game_result->select($where_last_week,'count(id) as last_week_play_nums');
            //过去一月闯关个数
            $last_month_play_result = $pass_game_result->select($where_last_month,'count(id) as last_month_play_nums');
            //全部闯关个数
            $all_play_result = $pass_game_result->select('','count(id) as all_play_nums');
            
            
            //取出所有关卡id
            $ka_ids = $this->db->select(' status=1 order by list_order asc','id');
            foreach ($ka_ids as $key=>$value){
                $ids[] = $value['id'];
            }
            $pass_result= array();
            foreach ($ids as $k=>$v){
                //当前关卡通过的次数
                $pass_play_result = $pass_game_result->select(' pass_game_id='.$v.' and is_success=1','count(id) as pass_nums');
                //当前关卡全部的次数
                $all_pass_play_result = $pass_game_result->select(' pass_game_id='.$v,'count(id) as all_pass_nums');
                
                $pass_result[$k]['pass_id'] = $v;
                $pass_result[$k]['pass_nums'] = $pass_play_result[0]['pass_nums'];#当前关卡的通过次数
                $pass_result[$k]['all_pass_nums'] = $all_pass_play_result[0]['all_pass_nums'];#当前关卡的全部玩耍次数
                $pass_result[$k]['pass_rate'] = round($pass_play_result[0]['pass_nums']/$all_pass_play_result[0]['all_pass_nums'],4)*100;//算当前关卡的通过率
            }
            $pass_result = serialize($pass_result);
            
            //记入cookie
            //用户数
            $today_user_num = $today_user_result[0]['today_user_nums'];
            $yesterday_user_num = $yesterday_user_result[0]['yesterday_user_nums'];
            $last_week_user_num = $last_week_user_result[0]['last_week_user_nums'];
            $last_month_user_num = $last_month_user_result[0]['last_month_user_nums'];
            $all_user_num = $all_user_result[0]['all_user_nums'];
            //闯关数
            $today_play_num = $today_play_result[0]['today_play_nums'];
            $yesterday_play_num = $yesterday_play_result[0]['yesterday_play_nums'];
            $last_week_play_num = $last_week_play_result[0]['last_week_play_nums'];
            $last_month_play_num = $last_month_play_result[0]['last_month_play_nums'];
            $all_play_num = $all_play_result[0]['all_play_nums'];
            
            setcookie("today_user_num", $today_user_num, time()+10);
            setcookie("yesterday_user_num", $yesterday_user_num, time()+10);
            setcookie("last_week_user_num", $last_week_user_num, time()+10);
            setcookie("last_month_user_num", $last_month_user_num, time()+10);
            setcookie("all_user_num", $all_user_num, time()+10);

            setcookie("today_play_num", $today_play_num, time()+10);
            setcookie("yesterday_play_num", $yesterday_play_num, time()+10);
            setcookie("last_week_play_num", $last_week_play_num, time()+10);
            setcookie("last_month_play_num", $last_month_play_num, time()+10);
            setcookie("all_play_num", $all_play_num, time()+10);
            setcache('pass_result',$pass_result);
        }
        include $this->admin_tpl('user_game_analysis');
    }
}